package com.ict.service.impl;

import com.ict.api.entity.IctProductCategory;
import com.ict.api.vo.IctProductCategoryVO;
import com.ict.mapper.IctProductCategoryMapper;
import com.ict.service.IctProductCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类表 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Service
public class IctProductCategoryServiceImpl extends ServiceImpl<IctProductCategoryMapper, IctProductCategory> implements IctProductCategoryService {

    @Resource
    private IctProductCategoryMapper productCategoryMapper;


    /**
     * 查询所有分类并构建树状结构
     */
    @Override
    public List<IctProductCategoryVO> findProductCategories() {
        // 查询所有未删除的分类
        List<IctProductCategory> allCategories = productCategoryMapper.selectList(null);

        List<IctProductCategoryVO> list = new ArrayList<>();

        allCategories.stream().forEach(item -> {
            IctProductCategoryVO ictProductCategoryVO = new IctProductCategoryVO();
            BeanUtils.copyProperties(item, ictProductCategoryVO);
            list.add(ictProductCategoryVO);
        });
        // 过滤出一级分类（parentId = 0）
        return list.stream()
                .filter(category -> category.getParentId().equals(0L))
                .peek(category -> category.setChildren(getChildren(category, list)))
                .collect(Collectors.toList());
    }

    /**
     * 递归获取子分类
     */
    private List<IctProductCategoryVO> getChildren(IctProductCategoryVO parent, List<IctProductCategoryVO> allCategories) {
        return allCategories.stream()
                .filter(category -> category.getParentId().equals(parent.getId()))
                .peek(category -> category.setChildren(getChildren(category, allCategories)))
                .collect(Collectors.toList());
    }
}
